import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Radio, InputNumber, Tabs, Transfer, Row, Col, Tooltip } from 'antd';
import { SearchOutlined, ReloadOutlined, SendOutlined, UserOutlined, TeamOutlined, FileExcelOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 获取优惠券列表
const fetchCoupons = async (params) => {
    return request('/api/v1/coupon', {
        method: 'GET',
        params: { ...params, status: 1 }, // 只获取状态为正常的优惠券
    });
};

// 获取会员列表
const fetchMembers = async (params) => {
    return request('/api/v1/member', {
        method: 'GET',
        params,
    });
};

// 发放优惠券
const issueCoupon = async (data) => {
    return request('/api/v1/coupon/issue', {
        method: 'POST',
        data,
    });
};

// 批量发放优惠券
const batchIssueCoupon = async (data) => {
    return request('/api/v1/coupon/batch_issue', {
        method: 'POST',
        data,
    });
};

// 获取优惠券发放记录
const fetchIssueRecords = async (params) => {
    return request('/api/v1/coupon/issue/list', {
        method: 'GET',
        params,
    });
};

// 获取会员等级列表
const fetchMemberLevels = async () => {
    return request('/api/v1/member/level/all', {
        method: 'GET',
        params: { status: 1 }, // 只获取状态为正常的会员等级
    });
};

const CouponIssue = () => {
    const [coupons, setCoupons] = useState([]);
    const [members, setMembers] = useState([]);
    const [records, setRecords] = useState([]);
    const [loading, setLoading] = useState(false);
    const [issueVisible, setIssueVisible] = useState(false);
    const [issueForm] = Form.useForm();
    const [searchForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchParams, setSearchParams] = useState({});
    const [issueType, setIssueType] = useState('single'); // single, batch, filter
    const [selectedMembers, setSelectedMembers] = useState([]);
    const [activeTab, setActiveTab] = useState('issue');
    const [filterForm] = Form.useForm();
    const [filterVisible, setFilterVisible] = useState(false);
    const [memberLevels, setMemberLevels] = useState([]); // 存储会员等级列表

    // 获取优惠券列表
    const fetchCouponList = async () => {
        if (loading) return; // 防止重复请求
        try {
            setLoading(true);
            const res = await fetchCoupons({});
            if (res.success) {
                setCoupons(res.data.list || []);
            } else {
                message.error(res.message || '获取优惠券列表失败');
            }
        } catch (error) {
            console.error('获取优惠券列表出错:', error);
            message.error('获取优惠券列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取会员列表
    const fetchMemberList = async () => {
        try {
            setLoading(true);
            const res = await fetchMembers({
                page: 1,
                pageSize: 100, // 获取较多会员以便选择
            });
            if (res.success) {
                setMembers(res.data.list || []);
            } else {
                message.error(res.message || '获取会员列表失败');
            }
        } catch (error) {
            console.error('获取会员列表出错:', error);
            message.error('获取会员列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取会员等级列表
    const fetchMemberLevelList = async () => {
        try {
            const res = await fetchMemberLevels();
            if (res.success) {
                setMemberLevels(res.data.list || []);
            } else {
                console.error('获取会员等级列表失败:', res.message);
            }
        } catch (error) {
            console.error('获取会员等级列表出错:', error);
        }
    };

    // 获取发放记录
    const fetchRecordList = async () => {
        try {
            setLoading(true);
            const res = await fetchIssueRecords({
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
            });
            
            if (res.success) {
                // 先获取所有需要的优惠券和会员ID
                const couponIds = new Set();
                const memberIds = new Set();
                (res.data.list || []).forEach(item => {
                    if (item.coupon_id) couponIds.add(item.coupon_id);
                    if (item.member_id) memberIds.add(item.member_id);
                });
                
                // 并行获取所有优惠券和会员信息
                let couponMap = {};
                let memberMap = {};
                
                try {
                    // 获取完整优惠券信息
                    if (couponIds.size > 0) {
                        const couponRes = await request('/api/v1/coupon/batch', {
                            method: 'POST',
                            data: { ids: Array.from(couponIds) }
                        });
                        if (couponRes.success) {
                            couponMap = (couponRes.data || []).reduce((map, item) => {
                                map[item.id] = item;
                                return map;
                            }, {});
                        }
                    }
                    
                    // 获取完整会员信息
                    if (memberIds.size > 0) {
                        const memberRes = await request('/api/v1/member/batch', {
                            method: 'POST',
                            data: { ids: Array.from(memberIds) }
                        });
                        if (memberRes.success) {
                            memberMap = (memberRes.data || []).reduce((map, item) => {
                                map[item.id] = item;
                                return map;
                            }, {});
                        }
                    }
                } catch (error) {
                    console.error('获取关联数据出错:', error);
                }
                
                // 处理返回的数据，确保字段名称正确并关联相关信息
                const processedList = (res.data.list || []).map(item => ({
                    ...item,
                    // 关联优惠券信息
                    coupon: item.coupon || couponMap[item.coupon_id] || {},
                    coupon_name: item.coupon_name || 
                                 (item.coupon?.name) || 
                                 (couponMap[item.coupon_id]?.name) || 
                                 '未知优惠券',
                    
                    // 关联会员信息
                    member: item.member || memberMap[item.member_id] || {},
                    member_name: item.member_name || 
                                 (item.member?.name) || 
                                 (memberMap[item.member_id]?.name) || 
                                 memberMap[item.member_id]?.phone || 
                                 '未知会员'
                }));
                
                setRecords(processedList);
                setPagination({
                    ...pagination,
                    total: res.data.total || 0,
                });
            } else {
                message.error(res.message || '获取发放记录失败');
            }
        } catch (error) {
            console.error('获取发放记录出错:', error);
            message.error('获取发放记录失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCouponList();
        fetchMemberList();
        fetchMemberLevelList(); // 获取会员等级
    }, []);

    useEffect(() => {
        if (activeTab === 'record') {
            fetchRecordList();
        }
    }, [activeTab, pagination.current, pagination.pageSize, searchParams]);

    useEffect(() => {
        const handleError = (error) => {
            console.error('全局错误捕获:', error);
            message.error('操作出错，请稍后重试');
        };

        window.addEventListener('unhandledrejection', handleError);
        return () => {
            window.removeEventListener('unhandledrejection', handleError);
        };
    }, []);

    // 处理发放优惠券
    const handleIssue = () => {
        setIssueType('single');
        issueForm.resetFields();
        setIssueVisible(true);
    };

    // 处理批量发放
    const handleBatchIssue = () => {
        setIssueType('batch');
        issueForm.resetFields();
        setSelectedMembers([]);
        setIssueVisible(true);
    };

    // 处理条件筛选发放
    const handleFilterIssue = () => {
        filterForm.resetFields();
        setFilterVisible(true);
    };

    // 提交发放
    const handleIssueSubmit = async () => {
        try {
            const values = await issueForm.validateFields();
            setLoading(true);

            let data = {
                coupon_id: values.couponId,
            };

            if (issueType === 'single') {
                data.member_id = values.memberId;
                const res = await issueCoupon(data);
                if (res.success) {
                    message.success('发放优惠券成功');
                    setIssueVisible(false);
                    if (activeTab === 'record') {
                        fetchRecordList();
                    }
                } else {
                    message.error(res.message || '发放优惠券失败');
                }
            } else if (issueType === 'batch') {
                data.member_ids = selectedMembers;
                const res = await batchIssueCoupon(data);
                if (res.success) {
                    message.success(`批量发放优惠券成功，成功${res.data.success_count}条，失败${res.data.fail_count}条`);
                    setIssueVisible(false);
                    if (activeTab === 'record') {
                        fetchRecordList();
                    }
                } else {
                    message.error(res.message || '批量发放优惠券失败');
                }
            }
        } catch (error) {
            console.error('发放优惠券出错:', error);
            message.error('发放优惠券失败');
        } finally {
            setLoading(false);
        }
    };

    // 提交条件筛选发放
    const handleFilterSubmit = async () => {
        try {
            const values = await filterForm.validateFields();
            setLoading(true);

            const data = {
                coupon_id: values.couponId,
                level: values.level,
            };

            if (values.regDateRange && values.regDateRange.length === 2) {
                data.reg_start_time = values.regDateRange[0].unix();
                data.reg_end_time = values.regDateRange[1].unix();
            }

            if (values.minConsume !== undefined) {
                data.min_consume = values.minConsume;
            }

            if (values.maxConsume !== undefined) {
                data.max_consume = values.maxConsume;
            }

            const res = await request('/api/v1/coupon/filter_issue', {
                method: 'POST',
                data,
            });

            if (res.success) {
                message.success(`条件筛选发放优惠券成功，成功${res.data.success_count}条，失败${res.data.fail_count}条`);
                setFilterVisible(false);
                if (activeTab === 'record') {
                    fetchRecordList();
                }
            } else {
                message.error(res.message || '条件筛选发放优惠券失败');
            }
        } catch (error) {
            console.error('条件筛选发放优惠券出错:', error);
            message.error('条件筛选发放优惠券失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.couponId) {
            params.coupon_id = values.couponId;
        }
        if (values.memberId) {
            params.member_id = values.memberId;
        }
        if (values.status !== undefined) {
            params.status = values.status;
        }
        if (values.dateRange?.length === 2) {
            params.start_time = values.dateRange[0].startOf('day').unix();
            params.end_time = values.dateRange[1].endOf('day').unix();
        }

        setSearchParams(params);
        setPagination({ ...pagination, current: 1 });
    };

    // 处理重置
    const handleReset = () => {
        searchForm.resetFields();
        setSearchParams({});
        setPagination({ ...pagination, current: 1 });
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 取消优惠券
    const handleCancel = async (id) => {
        try {
            setLoading(true);
            const res = await request('/api/v1/coupon/issue/cancel', {
                method: 'POST',
                data: { id },
            });
            if (res.success) {
                message.success('取消优惠券成功');
                fetchRecordList();
            } else {
                message.error(res.message || '取消优惠券失败');
            }
        } catch (error) {
            console.error('取消优惠券出错:', error);
            message.error('取消优惠券失败');
        } finally {
            setLoading(false);
        }
    };

    // 根据level_id获取会员等级名称
    const getMemberLevelName = (levelId) => {
        const level = memberLevels.find(level => level.id === levelId);
        return level ? level.name : '未知等级';
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
        },
        {
            title: '优惠券名称',
            dataIndex: 'coupon_name',
            key: 'coupon_name',
            render: (text, record) => (
                <Tooltip title={
                    <div>
                        <p><strong>名称：</strong>{record.coupon_name || record.coupon?.name}</p>
                        <p><strong>类型：</strong>{record.coupon?.type === 0 ? '满减券' : record.coupon?.type === 1 ? '折扣券' : '代金券'}</p>
                        <p><strong>价值：</strong>{record.coupon?.value}</p>
                        <p><strong>使用条件：</strong>满{record.coupon?.min_consume || 0}元可用</p>
                        <p><strong>描述：</strong>{record.coupon?.description || '无'}</p>
                    </div>
                }>
                    <span>{record.coupon_name || record.coupon?.name || text || '-'}</span>
                </Tooltip>
            ),
        },
        {
            title: '会员信息',
            dataIndex: 'member_name',
            key: 'member_name',
            render: (text, record) => (
                <Tooltip title={
                    <div>
                        <p><strong>名称：</strong>{record.member_name || record.member?.name}</p>
                        <p><strong>手机号：</strong>{record.member?.phone}</p>
                        <p><strong>等级：</strong>{getMemberLevelName(record.member?.level_id)}</p>
                        <p><strong>注册时间：</strong>{record.member?.created_at ? moment.unix(record.member.created_at).format('YYYY-MM-DD HH:mm') : '未知'}</p>
                    </div>
                }>
                    <div>
                        <div>{record.member_name || record.member?.name || '未知会员'}</div>
                        <div style={{ fontSize: '12px', color: '#999' }}>{record.member?.phone || '-'}</div>
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'green';
                let text = '未使用';
                if (status === 1) {
                    color = 'blue';
                    text = '已使用';
                } else if (status === 2) {
                    color = 'red';
                    text = '已过期';
                } else if (status === 3) {
                    color = 'gray';
                    text = '已取消';
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '有效期',
            key: 'valid_period',
            render: (_, record) => (
                <span>
                    {moment.unix(record.valid_from).format('YYYY-MM-DD')} 至 {moment.unix(record.valid_until).format('YYYY-MM-DD')}
                </span>
            ),
        },
        {
            title: '发放时间',
            dataIndex: 'created_at',
            key: 'created_at',
            render: (text) => <span>{moment.unix(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    {record.status === 0 && (
                        <Button type="link" onClick={() => handleCancel(record.id)}>
                            取消
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    return (
        <PageContainer>
            <Card>
                <Tabs defaultActiveKey="issue" onChange={setActiveTab}>
                    <TabPane tab="发放优惠券" key="issue">
                        <Space style={{ marginBottom: 16 }}>
                            <Button type="primary" icon={<UserOutlined />} onClick={handleIssue}>
                                单个发放
                            </Button>
                            <Button type="primary" icon={<TeamOutlined />} onClick={handleBatchIssue}>
                                批量发放
                            </Button>
                            <Button type="primary" icon={<SearchOutlined />} onClick={handleFilterIssue}>
                                条件筛选发放
                            </Button>
                        </Space>
                    </TabPane>
                    <TabPane tab="发放记录" key="record">
                        <Form form={searchForm} layout="inline" onFinish={handleSearch} style={{ marginBottom: 16 }}>
                            <Form.Item name="couponId" label="优惠券">
                                <Select placeholder="请选择" allowClear style={{ width: 150 }}>
                                    {coupons.map((coupon) => (
                                        <Option key={coupon.id} value={coupon.id}>
                                            {coupon.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                            <Form.Item name="memberId" label="会员">
                                <Select placeholder="请选择" allowClear style={{ width: 150 }}>
                                    {members.map((member) => (
                                        <Option key={member.id} value={member.id}>
                                            {member.name || member.phone}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                            <Form.Item name="status" label="状态">
                                <Select placeholder="请选择" allowClear style={{ width: 100 }}>
                                    <Option value={0}>未使用</Option>
                                    <Option value={1}>已使用</Option>
                                    <Option value={2}>已过期</Option>
                                    <Option value={3}>已取消</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item name="dateRange" label="发放时间">
                                <RangePicker style={{ width: 240 }} />
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                    搜索
                                </Button>
                            </Form.Item>
                            <Form.Item>
                                <Button onClick={handleReset} icon={<ReloadOutlined />}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Form>
                        <Table
                            columns={columns}
                            dataSource={records}
                            loading={loading}
                            pagination={pagination}
                            onChange={handleTableChange}
                            rowKey="id"
                        />
                    </TabPane>
                </Tabs>
            </Card>

            {/* 发放优惠券弹窗 */}
            <Modal
                title={issueType === 'single' ? '单个发放优惠券' : '批量发放优惠券'}
                visible={issueVisible}
                onOk={handleIssueSubmit}
                onCancel={() => setIssueVisible(false)}
                confirmLoading={loading}
                width={issueType === 'batch' ? 800 : 500}
            >
                <Form form={issueForm} layout="vertical">
                    <Form.Item
                        name="couponId"
                        label="选择优惠券"
                        rules={[{ required: true, message: '请选择优惠券' }]}
                    >
                        <Select placeholder="请选择优惠券">
                            {coupons.map((coupon) => (
                                <Option key={coupon.id} value={coupon.id}>
                                    {coupon.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {issueType === 'single' && (
                        <Form.Item
                            name="memberId"
                            label="选择会员"
                            rules={[{ required: true, message: '请选择会员' }]}
                        >
                            <Select
                                placeholder="请选择会员"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            >
                                {members.map((member) => (
                                    <Option key={member.id} value={member.id}>
                                        {member.name || member.phone}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    )}

                    {issueType === 'batch' && (
                        <Form.Item
                            name="memberIds"
                            label="选择会员"
                            rules={[{ required: true, message: '请选择至少一个会员' }]}
                        >
                            <Transfer
                                dataSource={members.map(member => ({
                                    key: member.id,
                                    title: member.name || member.phone,
                                }))}
                                titles={['可选会员', '已选会员']}
                                targetKeys={selectedMembers}
                                onChange={setSelectedMembers}
                                render={item => item.title}
                                listStyle={{ width: 300, height: 300 }}
                            />
                        </Form.Item>
                    )}
                </Form>
            </Modal>

            {/* 条件筛选发放弹窗 */}
            <Modal
                title="条件筛选发放优惠券"
                visible={filterVisible}
                onOk={handleFilterSubmit}
                onCancel={() => setFilterVisible(false)}
                confirmLoading={loading}
                width={600}
            >
                <Form form={filterForm} layout="vertical">
                    <Form.Item
                        name="couponId"
                        label="选择优惠券"
                        rules={[{ required: true, message: '请选择优惠券' }]}
                    >
                        <Select placeholder="请选择优惠券">
                            {coupons.map((coupon) => (
                                <Option key={coupon.id} value={coupon.id}>
                                    {coupon.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="level" label="会员等级">
                        <Select placeholder="请选择会员等级" allowClear>
                            {memberLevels.map((level) => (
                                <Option key={level.id} value={level.id}>
                                    {level.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="regDateRange" label="注册时间范围">
                        <RangePicker style={{ width: '100%' }} />
                    </Form.Item>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item 
                                name="minConsume" 
                                label="最低消费金额"
                                rules={[
                                    { type: 'number', min: 0, message: '最低消费金额不能小于0' }
                                ]}
                            >
                                <InputNumber min={0} style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item 
                                name="maxConsume" 
                                label="最高消费金额"
                                rules={[
                                    { type: 'number', min: 0, message: '最高消费金额不能小于0' },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!value || !getFieldValue('minConsume') || value >= getFieldValue('minConsume')) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject(new Error('最高消费金额必须大于最低消费金额'));
                                        },
                                    }),
                                ]}
                            >
                                <InputNumber min={0} style={{ width: '100%' }} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default CouponIssue;